package com.hsy.sunflowerbao.base.ui.widget

import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Animatable
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Build
import android.support.annotation.DrawableRes
import android.support.annotation.RequiresApi
import android.support.v4.app.FragmentActivity
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import android.widget.ImageView
import android.widget.RelativeLayout

import com.scwang.smartrefresh.layout.api.RefreshHeader
import com.scwang.smartrefresh.layout.api.RefreshKernel
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.constant.RefreshState
import com.scwang.smartrefresh.layout.constant.SpinnerStyle
import com.scwang.smartrefresh.layout.internal.ProgressDrawable
import com.scwang.smartrefresh.layout.util.DensityUtil

import com.scwang.smartrefresh.layout.constant.RefreshState.*

/**
 * 自定义下拉头部
 * Created on 2017/9/6.
 *
 * @author Yang
 */
class CustomerHeader : RelativeLayout, RefreshHeader {

    /**
     * 进度控件
     */
    lateinit var progressView: ImageView
        protected set
    /**
     * RefreshKernel
     */
    protected var mRefreshKernel: RefreshKernel? = null
    /**
     * 进度图
     */
    protected var mProgressDrawable: ProgressDrawable? = null
    /**
     * 下拉效果
     */
    protected var mSpinnerStyle = SpinnerStyle.Translate
    protected var mFinishDuration = 500
    protected var mBackgroundColor: Int = 0
    protected var mPaddingTop = 20
    protected var mPaddingBottom = 20

    private var restoreRunable: Runnable? = null

    constructor(context: Context) : super(context) {
        this.initView(context, null)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        this.initView(context, attrs)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        this.initView(context, attrs)
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
        this.initView(context, attrs)
    }

    private fun initView(context: Context, attrs: AttributeSet?) {
        val density = DensityUtil()

        val lpArrow = RelativeLayout.LayoutParams(density.dip2px(20f), density.dip2px(20f))

        val lpProgress = RelativeLayout.LayoutParams(lpArrow as ViewGroup.LayoutParams)
        lpProgress.addRule(RelativeLayout.CENTER_IN_PARENT)
        progressView = ImageView(context)
        progressView.animate().interpolator = LinearInterpolator()
        addView(progressView, lpProgress)

        val ta = context.obtainStyledAttributes(attrs, com.scwang.smartrefresh.layout.R.styleable.ClassicsHeader)

        lpArrow.width = ta.getLayoutDimension(com.scwang.smartrefresh.layout.R.styleable.ClassicsHeader_srlDrawableArrowSize, lpArrow.width)
        lpArrow.height = ta.getLayoutDimension(com.scwang.smartrefresh.layout.R.styleable.ClassicsHeader_srlDrawableArrowSize, lpArrow.height)
        lpProgress.width = ta.getLayoutDimension(com.scwang.smartrefresh.layout.R.styleable.ClassicsHeader_srlDrawableProgressSize, lpProgress.width)
        lpProgress.height = ta.getLayoutDimension(com.scwang.smartrefresh.layout.R.styleable.ClassicsHeader_srlDrawableProgressSize, lpProgress.height)

        lpArrow.width = ta.getLayoutDimension(com.scwang.smartrefresh.layout.R.styleable.ClassicsHeader_srlDrawableSize, lpArrow.width)
        lpArrow.height = ta.getLayoutDimension(com.scwang.smartrefresh.layout.R.styleable.ClassicsHeader_srlDrawableSize, lpArrow.height)
        lpProgress.width = ta.getLayoutDimension(com.scwang.smartrefresh.layout.R.styleable.ClassicsHeader_srlDrawableSize, lpProgress.width)
        lpProgress.height = ta.getLayoutDimension(com.scwang.smartrefresh.layout.R.styleable.ClassicsHeader_srlDrawableSize, lpProgress.height)

        mFinishDuration = ta.getInt(com.scwang.smartrefresh.layout.R.styleable.ClassicsHeader_srlFinishDuration, mFinishDuration)
        mSpinnerStyle = SpinnerStyle.values()[ta.getInt(com.scwang.smartrefresh.layout.R.styleable.ClassicsHeader_srlClassicsSpinnerStyle, mSpinnerStyle.ordinal)]

        if (ta.hasValue(com.scwang.smartrefresh.layout.R.styleable.ClassicsHeader_srlDrawableProgress)) {
            progressView.setImageDrawable(ta.getDrawable(com.scwang.smartrefresh.layout.R.styleable.ClassicsHeader_srlDrawableProgress))
        } else {
            mProgressDrawable = ProgressDrawable()
            mProgressDrawable!!.setColor(-0x99999a)
            progressView.setImageDrawable(mProgressDrawable)
        }

        ta.recycle()

        if (paddingTop == 0) {
            if (paddingBottom == 0) {
                setPadding(paddingLeft, density.dip2px(20f), paddingRight, density.dip2px(20f))
            } else {
                setPadding(paddingLeft, density.dip2px(20f), paddingRight, paddingBottom)
            }
        } else {
            if (paddingBottom == 0) {
                setPadding(paddingLeft, paddingTop, paddingRight, density.dip2px(20f))
            } else {
                mPaddingTop = paddingTop
                mPaddingBottom = paddingBottom
            }
        }

        try {//try 不能删除-否则会出现兼容性问题
            if (context is FragmentActivity) {
                val manager = context.supportFragmentManager
                if (manager != null) {
                    val fragments = manager.fragments
                    if (fragments != null && fragments.size > 0) {
                        return
                    }
                }
            }
        } catch (e: Throwable) {
            e.printStackTrace()
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        if (View.MeasureSpec.getMode(heightMeasureSpec) == View.MeasureSpec.EXACTLY) {
            setPadding(paddingLeft, 0, paddingRight, 0)
        } else {
            setPadding(paddingLeft, mPaddingTop, paddingRight, mPaddingBottom)
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

    override fun onInitialized(kernel: RefreshKernel, height: Int, extendHeight: Int) {
        mRefreshKernel = kernel
        mRefreshKernel!!.requestDrawBackgroundForHeader(mBackgroundColor)
    }

    override fun isSupportHorizontalDrag(): Boolean {
        return false
    }

    override fun onHorizontalDrag(percentX: Float, offsetX: Int, offsetMax: Int) {}

    override fun onPulling(percent: Float, offset: Int, headHeight: Int, extendHeight: Int) {}

    override fun onReleasing(percent: Float, offset: Int, headHeight: Int, extendHeight: Int) {

    }

    override fun onReleased(layout: RefreshLayout, headerHeight: Int, extendHeight: Int) {
        if (mProgressDrawable != null) {
            mProgressDrawable!!.start()
        } else {
            val drawable = progressView.drawable
            if (drawable is Animatable) {
                (drawable as Animatable).start()
            } else {
                progressView.animate().rotation(36000f).duration = 100000
            }
        }
    }

    override fun onStartAnimator(layout: RefreshLayout, headHeight: Int, extendHeight: Int) {

    }

    override fun onFinish(layout: RefreshLayout, success: Boolean): Int {
        if (mProgressDrawable != null) {
            mProgressDrawable!!.stop()
        } else {
            val drawable = progressView.drawable
            if (drawable is Animatable) {
                (drawable as Animatable).stop()
            } else {
                progressView.animate().rotation(0f).duration = 10
            }
        }
        progressView.visibility = View.VISIBLE
        return mFinishDuration//延迟500毫秒之后再弹回
    }

    @Deprecated("")
    override fun setPrimaryColors(vararg colors: Int) {
        if (colors.isNotEmpty()) {
            if (background !is BitmapDrawable) {
                setPrimaryColor(colors[0])
            }
            if (colors.size > 1) {
                setAccentColor(colors[1])
            } else {
                setAccentColor(if (colors[0] == -0x1) -0x99999a else -0x1)
            }
        }
    }

    override fun getView(): View {
        return this
    }

    override fun getSpinnerStyle(): SpinnerStyle {
        return mSpinnerStyle
    }

    override fun onStateChanged(refreshLayout: RefreshLayout, oldState: RefreshState, newState: RefreshState) {
        when (newState) {
            None, PullDownToRefresh -> {
                progressView.visibility = View.VISIBLE
            }
            Refreshing -> {
                progressView.visibility = View.VISIBLE
            }
            Loading -> {
                progressView.visibility = View.GONE
            }
            else -> {
            }
        }
    }

    private fun restoreRefreshLayoutBackground() {
        if (restoreRunable != null) {
            restoreRunable!!.run()
            restoreRunable = null
        }
    }

    private fun replaceRefreshLayoutBackground(refreshLayout: RefreshLayout) {
        if (restoreRunable == null && mSpinnerStyle == SpinnerStyle.FixedBehind) {
            restoreRunable = object : Runnable {
                internal var drawable = refreshLayout.layout.background

                override fun run() {
                    refreshLayout.layout.background = drawable
                }
            }
            refreshLayout.layout.background = background
        }
    }

    fun setProgressBitmap(bitmap: Bitmap): CustomerHeader {
        mProgressDrawable = null
        progressView.setImageBitmap(bitmap)
        return this
    }

    fun setProgressDrawable(drawable: Drawable): CustomerHeader {
        mProgressDrawable = null
        progressView.setImageDrawable(drawable)
        return this
    }

    fun setProgressResource(@DrawableRes resId: Int): CustomerHeader {
        mProgressDrawable = null
        progressView.setImageResource(resId)
        return this
    }

    fun setSpinnerStyle(style: SpinnerStyle): CustomerHeader {
        this.mSpinnerStyle = style
        return this
    }

    fun setPrimaryColor(primaryColor: Int): CustomerHeader {
        setBackgroundColor(primaryColor)
        if (mRefreshKernel != null) {
            mRefreshKernel!!.requestDrawBackgroundForHeader(mBackgroundColor)
        }
        return this
    }

    fun setAccentColor(accentColor: Int): CustomerHeader {
        if (mProgressDrawable != null) {
            mProgressDrawable!!.setColor(accentColor)
        }
        return this
    }

    fun setFinishDuration(delay: Int): CustomerHeader {
        mFinishDuration = delay
        return this
    }

    fun setTextSizeTitle(size: Float): CustomerHeader {
        if (mRefreshKernel != null) {
            mRefreshKernel!!.requestRemeasureHeightForHeader()
        }
        return this
    }

    fun setTextSizeTitle(unit: Int, size: Float): CustomerHeader {
        if (mRefreshKernel != null) {
            mRefreshKernel!!.requestRemeasureHeightForHeader()
        }
        return this
    }

    fun setDrawableMarginRight(dp: Float): CustomerHeader {
        return setDrawableMarginRightPx(DensityUtil.dp2px(dp))
    }

    fun setDrawableMarginRightPx(px: Int): CustomerHeader {
        val lpProgress = progressView.layoutParams as ViewGroup.MarginLayoutParams
        progressView.layoutParams = lpProgress
        return this
    }

    fun setDrawableSize(dp: Float): CustomerHeader {
        return setDrawableSizePx(DensityUtil.dp2px(dp))
    }

    fun setDrawableSizePx(px: Int): CustomerHeader {
        val lpProgress = progressView.layoutParams
        progressView.layoutParams = lpProgress
        return this
    }

    fun setDrawableProgressSize(dp: Float): CustomerHeader {
        return setDrawableProgressSizePx(DensityUtil.dp2px(dp))
    }

    fun setDrawableProgressSizePx(px: Int): CustomerHeader {
        val lpProgress = progressView.layoutParams
        lpProgress.width = px
        lpProgress.height = px
        progressView.layoutParams = lpProgress
        return this
    }
}